package com.zhkj.txg.module.find.ui

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import android.view.ViewTreeObserver
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.google.android.material.appbar.AppBarLayout
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.find.adapter.FindBannerAdapter
import com.zhkj.txg.module.find.adapter.FindCommentAdapter
import com.zhkj.txg.module.find.entity.FindArticleDetailEntity
import com.zhkj.txg.module.find.popup.FindCommentInputPopupWindow
import com.zhkj.txg.module.find.vm.FindViewModel
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import com.zhkj.txg.module.product.ui.WatcherActivity
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_find_article_detail.*
import razerdp.util.KeyboardUtils
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min

class FindArticleDetailActivity : ViewModelActivity<FindViewModel>() {

    companion object {
        private val KEY_ID = "key"

        fun openDetail(context: Context, id: Int) {
            val intent = Intent(context, FindArticleDetailActivity::class.java)
                .putExtra(KEY_ID, id)
            context.startActivity(intent)
        }
    }

    override fun setViewModel(): FindViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleFindArticle
    override val layoutResId: Int = R.layout.activity_find_article_detail

    private var findArticleId = 0
    private var bannerHeight: Int = 0

    // 评论Adapter
    private val commentAdapter = FindCommentAdapter()
        .apply {
            loadMoreModule?.isEnableLoadMoreIfNotFullPage = true
            loadMoreModule?.setOnLoadMoreListener {
                viewModel.findArticleCommentList(AccountManager.getToken(), findArticleId)
            }
            setOnItemChildClickListener { _, view, position ->
                if (AccountManager.getToken().isBlank()) {
                    toast(getString(R.string.please_login))
                    return@setOnItemChildClickListener
                }
                val comment = data[position]
                when (view.id) {
                    R.id.viewFindCommentLike -> {// 评论点赞
                        viewModel.likeFind(
                            AccountManager.getToken(),
                            findArticleId,
                            comment.id,
                            1,
                            position
                        )
                    }
                    R.id.tvFindArticleCommentDelete -> {// 删除评论
                        viewModel.deleteComment(
                            AccountManager.getToken(),
                            findArticleId,
                            comment.id,
                            position
                        )
                    }
                }
            }
        }

    // 输入框popupWindow
    private val inputPopup: FindCommentInputPopupWindow by lazy {
        FindCommentInputPopupWindow(this, { content -> // 确认提交评论
            viewModel.commentCommit(AccountManager.getToken(), findArticleId, 0, content)
        }, {// 输入框关闭时将文字赋值
            tvFindArticleComment.text = inputPopup.getContent()
        })
    }
    private var globalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null

    override fun initUI() {
        // 获取色值变化的高度
        titleFindArticle.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                bannerHeight =
                    ScreenUtil.getScreenWidth(this@FindArticleDetailActivity) - titleFindArticle.measuredHeight
                titleFindArticle.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        // 监听滚动
        appBarFind.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val realY = abs(verticalOffset)
            if (realY <= bannerHeight) {
                val alpha = realY.toFloat() / bannerHeight * 255
                titleFindArticle.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
            } else titleFindArticle.setBackgroundColor(Color.WHITE)
        })
        // 设置Adapter
        rvFind.layoutManager = LinearLayoutManager(this)
        rvFind.adapter = commentAdapter
        (rvFind.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
        commentAdapter.setEmptyView(R.layout.layout_empty_data)
        // 弹出键盘点击事件
        tvFindArticleComment.setOnClickListener {
            inputPopup.setContent(tvFindArticleComment.text?.toString() ?: "")
            inputPopup.showPopupWindow()
        }
        // 添加键盘监听
        globalLayoutListener = KeyboardUtils.observerKeyboardChange(this) { _, isVisible ->
            if (!isVisible && inputPopup.isShowing) inputPopup.dismiss()
        }
        // 设置点赞监听
        viewLike.setOnClickListener {
            if (AccountManager.getToken().isBlank()) {
                toast(getString(R.string.please_login))
                return@setOnClickListener
            }
            viewModel.likeFind(AccountManager.getToken(), findArticleId, 0, 0, 0)
        }
        viewFIndGoods.setOnClickListener {
            viewModel.findArticleLiveData.value?.response?.data?.goods?.let {
                ProductDetailActivity.normalProduct(this, it.id, true)
            }
        }
        bannerFind.addBannerLifecycleObserver(this).setAdapter(FindBannerAdapter(this))
            .setOnBannerListener { _, position ->
                viewModel.findArticleLiveData.value?.response?.data?.images?.let {
                    if (it.isNotEmpty()) {
                        val list = ArrayList<String>()
                        list.addAll(it)
                        WatcherActivity.open(this, list, position)
                    }
                }
            }
    }

    override fun onDestroy() {
        // 销毁键盘监听
        if (globalLayoutListener != null)
            window.decorView.viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutListener)
        super.onDestroy()
    }

    override fun initViewModel() {
        // 发现文章评论列表数据观察者
        viewModel.findCommentLiveData.observe(this, Observer { it ->
            when (it.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> it.response?.let {
                    // 数据填充
                    if (it.isLoadMore) commentAdapter.addData(it.data)
                    else commentAdapter.setNewData(it.data)
                    // 判断加载状态
                    if (it.hasMore) commentAdapter.loadMoreModule?.loadMoreComplete()
                    else commentAdapter.loadMoreModule?.loadMoreEnd()
                }
                HttpResponseStatus.Status.FAILURE -> {
                    it.exception?.printStackTrace()
                    toast(it.statusTip)
                    commentAdapter.loadMoreModule?.loadMoreFail()
                }
            }
        })
        // 发现文章发表评论观察者
        viewModel.commentCommitLiveData.observe(this@FindArticleDetailActivity, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(getString(R.string.comment_success))
                viewModel.findArticleCommentList(AccountManager.getToken(), findArticleId, true)
                tvFindArticleComment.text = ""
                inputPopup.setContent("")
                inputPopup.dismiss()
            }
        })
        // 点赞发现文章观察者
        viewModel.likeLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                val like = viewLike.isSelected
                val currentLikeCount = tvArticleLike.text.toString().toInt()
                if (like) tvArticleLike.text = min(currentLikeCount - 1, 0).toString()
                else tvArticleLike.text = (currentLikeCount + 1).toString()
                viewLike.isSelected = !like
            }
        })
        // 评论点赞观察者
        viewModel.likeCommentLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.let {
                    val likeArticle = commentAdapter.data[it.uiIndex].likeArticle
                    if (likeArticle) {
                        commentAdapter.data[it.uiIndex].likes =
                            max(commentAdapter.data[it.uiIndex].likes - 1, 0)
                    } else commentAdapter.data[it.uiIndex].likes += 1
                    commentAdapter.data[it.uiIndex].likeArticle = !likeArticle
                    commentAdapter.notifyItemChanged(it.uiIndex)
                }
            }
        })
        // 评论删除观察者
        viewModel.deleteCommentLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.let {
                    commentAdapter.data.removeAt(it.uiIndex)
                    commentAdapter.notifyItemRemoved(it.uiIndex)
                }
            }
        })
    }

    override fun initData() {
        findArticleId = intent.getIntExtra(KEY_ID, -1)
        val token = AccountManager.getToken()
        viewModel.findArticleDetail(token, findArticleId).takeIf {
            !it.hasObservers()
        }?.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) it.response?.data?.let {
                setFindArticleData(it)
            }
        })
    }

    /**
     * 填充发现文章详情
     */
    private fun setFindArticleData(response: FindArticleDetailEntity) {
        if (response.images.isNotEmpty()) {
            bannerFind.adapter.setDatas(response.images)
            bannerFind.adapter.notifyDataSetChanged()
            bannerFind.start()
        }
        tvFindTitle.text = response.content
        tvFindArticleCreateTime.text = response.createTime
        viewLike.isSelected = response.likeArticle
        tvArticleLike.text = response.likes.toString()
        response.user?.let {
            ImageUtils.loadCircleImage(this, ivFindArticleUser, it.avatar)
            tvFindArticleUserName.text = it.nickname
        }
        response.goods?.let {
            viewFIndGoods.visibility = View.VISIBLE
            ImageUtils.loadRoundCornerImage(this, ivFindGoods, it.image)
            tvFindGoodsTitle.text = it.goodsName
            // 设置是显示市场价还是显示分享赚多少钱
            tvFindGoodsPrice.text = SpanUtil.setMoneySymbol(it.price, true)
            with(tvFindGoodsMarketPrice) {
                if (AccountManager.isMember() && it.shareEarn.isNotEmpty() && it.shareEarn != "0") {
                    setTextColor(ContextCompat.getColor(context, R.color.colorMain))
                    paint.flags = Paint.ANTI_ALIAS_FLAG
                    text = SpanUtil.setPrefixMoneyStr(price = it.shareEarn)
                } else {
                    setTextColor(ContextCompat.getColor(context, R.color.colorLightText))
                    paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    paint.isAntiAlias = true
                    text = SpanUtil.setMoneySymbol(it.marketPrice)
                }
            }
//            tvFindGoodsMarketPrice.text = SpanUtil.setMoneySymbol(it.marketPrice)
        }
    }
}